package com.boarsoft.boar.demo.order.action;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.demo.order.entity.PocOrder;
import com.boarsoft.boar.demo.order.service.PocOrderService;
import com.boarsoft.cache.Cache;
import com.boarsoft.common.Authorized;
import com.boarsoft.common.Util;
import com.boarsoft.flow.core.SimpleFlow;
import com.boarsoft.flow.core.SimpleFlowEngine;

@RestController
@RequestMapping("/order")
public class PocOrderAction {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private Cache redisCache;
	@Autowired
	private SimpleFlowEngine flowEngine;
	@Autowired
	private PocOrderService orderSvc;

	@RequestMapping("/finish.do")
	@Authorized(code = "order.finish")
	public ReplyInfo<Object> finish(Integer orderId, Integer tenantId, Boolean callType) {
		// PocOrder o = new PocOrder();
		// o.setOrderId(orderId);
		// o.setTenantId(tenantId);
		// return orderService.finish(o, callType)//
		// ? ReplyInfo.SUCCESS : ReplyInfo.FAILED;
//		return ReplyInfo.SUCCESS;
		return new ReplyInfo<Object>("zzzzz");
	}

	@RequestMapping("/find.do")
	@Authorized(code = "order.find")
	public ReplyInfo<Object> find(Integer tenantId, Integer orderId) {
		PocOrder o = orderSvc.find(tenantId, orderId);
		return new ReplyInfo<Object>(true, o);
	}

	@RequestMapping("/place.do")
	@Authorized(code = "order.place")
	public ReplyInfo<Object> place(PocOrder o) {
		// 创建订单
		o.setStatus(PocOrder.STATUS_PLACE);
		o.setCreateTime(Util.getStdmfDateTime());
		o.setModifyTime(o.getCreateTime());
		// 减库存
		long s = redisCache.incr("store", String.valueOf(//
				o.getProductId()), -o.getProductNum());
		if (s < 0) {
			// 还原库存
			s = redisCache.incr("store", String.valueOf(//
					o.getProductId()), +o.getProductNum());
			log.warn("Store of product {} is {}", o.getProductId(), s);
			return ReplyInfo.FAILED;
		}
		// 获取订单号
		long id = redisCache.incr("default", "order_id", 1);
		o.setOrderId((int) id);
		// 生成订单
		try {
			SimpleFlow f = flowEngine.start("placeOrderFlow", o);
			return new ReplyInfo<Object>(true, f.getData());
		} catch (Throwable e) {
			log.error("Error on start placeOrderFlow", e);
			// TODO 错误处理
			return new ReplyInfo<Object>(e.getMessage());
		}
	}
}